package base

import (
	"errors"
	"net/http"
	"walnut/internal/model/base"
	"walnut/kernel"
)

// 创建菜单
func CreateMenu(w http.ResponseWriter, r *http.Request) {
	var menu base.Menu
	if kernel.Qe(w, kernel.ShouldBindJSON(r, &menu)) {
		return
	}

	// 检查输入参数
	if menu.Name == "" {
		kernel.Error(w, errors.New("菜单名称不能为空"))
		return
	}

	_, err := kernel.DB.Exec("INSERT INTO menu (name, parent_id, url, sort) VALUES (?, ?, ?, ?)", menu.Name, menu.ParentID, menu.URL, menu.Sort)
	if err != nil {
		kernel.Error(w, err)
		return
	}

	kernel.Success(w)
}

// 获取菜单列表
func GetMenus(w http.ResponseWriter, r *http.Request) {
	var request base.CreateMenuRequest
	if kernel.Qe(w, kernel.ShouldBindJSON(r, &request)) {
		return
	}

	// 查询总记录数
	var total int64
	err := kernel.DB.QueryRow("SELECT COUNT(*) FROM menu").Scan(&total)
	if err != nil {
		kernel.Error(w, err)
		return
	}

	// 分页查询
	rows, err := kernel.DB.Query("SELECT id, name, parent_id, url, sort FROM menu ORDER BY sort ASC LIMIT ? OFFSET ?", request.GetSize(), request.Offset())
	if err != nil {
		kernel.Error(w, err)
		return
	}
	defer rows.Close()

	var menus []base.Menu
	for rows.Next() {
		var menu base.Menu
		if err := rows.Scan(&menu.ID, &menu.Name, &menu.ParentID, &menu.URL, &menu.Sort); err != nil {
			kernel.Error(w, err)
			return
		}
		menus = append(menus, menu)
	}

	// 返回带分页信息的数据
	kernel.List(w, total, request.GetPage(), request.GetSize(), menus)
}

// 更新菜单
func UpdateMenu(w http.ResponseWriter, r *http.Request) {
	var menu base.Menu
	if kernel.Qe(w, kernel.ShouldBindJSON(r, &menu)) {
		return
	}

	_, err := kernel.DB.Exec("UPDATE menu SET name = ?, parent_id = ?, url = ?, sort = ? WHERE id = ?", menu.Name, menu.ParentID, menu.URL, menu.Sort, menu.ID)
	if err != nil {
		kernel.Error(w, err)
		return
	}

	kernel.Success(w)
}

// 删除菜单
func DeleteMenu(w http.ResponseWriter, r *http.Request) {
	var menu base.Menu
	if kernel.Qe(w, kernel.ShouldBindJSON(r, &menu)) {
		return
	}

	_, err := kernel.DB.Exec("DELETE FROM menu WHERE id = ?", menu.ID)
	if err != nil {
		kernel.Error(w, err)
		return
	}

	kernel.Success(w)
}
